import { useState, useMemo } from "react";

// 全量的左侧菜单数据
import { menuRoutes } from "@/router";
import { useAppSelector } from ".";
import { genPaths } from "@/utils";
import { RouteObject } from "react-router-dom";

// 定义一个递归函数
function dep(allPermission: string[], menuRoutes: RouteObject[]) {
  return menuRoutes
    .filter((route) => allPermission.includes(route.key))
    .map((route) => {
      // 最后会修改 route.children，为了避免修改到原数据，简单做一个浅拷贝
      const curRoute = { ...route };

      if (curRoute.children?.length) {
        // 有children，使用 children 再过滤一遍
        curRoute.children = dep(allPermission, curRoute.children);
      }

      return curRoute;
    });
}

export const useMenu = () => {
  // 当前用户的权限数据
  const permission: string[] = useAppSelector(
    (state) => state.user.checkedkeys
  );
  const role = useAppSelector((state) => state.user.role);

  // permission 数据的格式 ['/dashboard/workplace']
  // 这种格式没有父级，我们需要处理一下   ['/dashboard', '/dashboard/workplace']
  // '/dashboard/workplace'  =>  ['/dashboard', '/dashboard/workplace']
  // '/a/b/c/d'              =>  ['/a', '/a/b', '/a/b/c', '/a/b/c/d']

  const allPermission = useMemo(() => {
    let result: string[] = []; // 最终结果
    permission.forEach((key) => {
      // 调用 usePath(key) => 得到一份数组
      const tmp = genPaths(key);
      // 将 tmp 收到到 result 中
      result.push(...tmp);
    });
    // 数组去重
    return Array.from(new Set(result));
  }, permission);

  // 基于 permission 于 menuRoutes 生成一份 permissionMenus
  const permissionMenus = useMemo(() => {
    if (role === 2) {
      // 超级管理员，拥有全部的权限
      return menuRoutes;
    }
    return dep(allPermission, menuRoutes);
  }, [allPermission]);

  return {
    permission,
    allPermission,
    permissionMenus,
  };
};
